<template>
  <div>
    <el-tag :key="tag" v-for="tag in model" closable :disable-transitions="false" @close="handleClose(tag)"
      size="small">
      {{tag}}
    </el-tag>
    <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="mini"
      @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
    </el-input>
    <yc-button v-if="inputVisible === false && model && maxLength > model.length" class="button-new-tag" size="mini"
      @click="showInput">+添加</yc-button>
  </div>
</template>
<script>
export default {
  name: 'yc-tag-dynamic',
  componentName: 'yc-tag-dynamic',
  props: {
    value: {
      type: [Array],
      default: null
    },
    maxLength: {
      type: [Number],
      default: 3
    }
  },
  data () {
    return {
      inputVisible: false,
      inputValue: ''
    }
  },
  computed: {
    model: {
      get () {
        return this.value
      },
      set (val) {
        this.$emit('input', val)
        this.$emit('change', val)
      }
    },
    listeners () {
      return {
        ...this.$listeners
      }
    }
  },
  methods: {
    handleClose (tag) {
      this.model.splice(this.model.indexOf(tag), 1)
    },

    showInput () {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm () {
      let inputValue = this.inputValue
      if (inputValue && this.model.indexOf(inputValue) < 0) {
        this.model.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    }
  }
}
</script>
<style lang="scss" scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
